package cn.softgame.cms.common.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class FreeMarkerUtil {
	private static FreeMarkerUtil instance = new FreeMarkerUtil();
	private Configuration cfg = null;
	private FreeMarkerUtil(){
		cfg = new Configuration();
		cfg.setClassForTemplateLoading(getClass(), "/template");
		// 指定模板如何检索数据模型
		cfg.setObjectWrapper(new DefaultObjectWrapper());
	}
	
	public static FreeMarkerUtil getInstance(){
		return instance;
	}
	
	public Configuration getConfiguration(){
		return cfg;
	}
	
	public Template getTemplate(String template){
		Template temp = null;
		try {
			temp = cfg.getTemplate(template);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return temp;
	}
	/*public static void main(String[] args) throws IOException, TemplateException {
		FreeMarkerUtil freemarker = FreeMarkerUtil.getInstance();
		// 创建根哈希表
		Map<String,String> root = new HashMap<String,String>();
		root.put("customerName", "Google");
		root.put("url", "http://localhost:8080/ipran");
		root.put("resetPwdLink", "http://localhost:8080/ipran/public/forgotPwd.html?x=8b3e19e6088c2b19f59a20fd03c8ad9e");
		root.put("requestDate", "2012-12-19 10:20:53");
		root.put("sendMailDate", "2011-12-29");
		Template temp = freemarker.getTemplate("resetPwd.ftl");
		 将模板和数据模型合并 
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		Writer out = new OutputStreamWriter(bos,"UTF-8");
		temp.process(root, out);
		String content = bos.toString();
		System.out.println(content);
		bos.close();
		out.close();
	}*/
}
